package com.atguigu.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Member;
import com.atguigu.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    private MemberService memberService;
   @Autowired
   private JedisPool jedisPool;
    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){//validateCode  telephone
        //1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        String validateCode = (String)map.get("validateCode");
        String telephone = (String)map.get("telephone");//来自表单的校验码
        String redisCode=jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        if(redisCode==null || !redisCode.equalsIgnoreCase(validateCode)){//
            return new Result(false, MessageConstant.VALIDATECODE_NOTNULL_ERROR);
        }
        //2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
        Member member=memberService.findMemberByTelehone(telephone);
        if(member==null){
            member =new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.save(member);
        }
        //3、向客户端写入Cookie，内容为用户手机号

        Cookie cookie = new Cookie("login_member_telephone", telephone);
//        表示谁都可以获取
        cookie.setPath("/");
        cookie.setMaxAge(30*24*60*60);
        response.addCookie(cookie);
//        此时return的话cookie也会被返回
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
